package cn.lblbc.appassit.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import java.io.File

/**
 * 导出结果对话框帮助类
 * 提供统一的导出成功界面和相关功能
 */
class ExportResultDialogHelper(private val context: Context) {

    /**
     * 显示导出结果对话框
     */
    fun showExportResultDialog(result: AppExporter.ExportResult) {
        val message = buildString {
            appendLine("✅ 导出完成!")
            appendLine()
            appendLine("📁 导出路径:")
            appendLine(result.exportPath)
            appendLine()
            appendLine("📊 导出统计:")
            appendLine("• 总数: ${result.totalCount}")
            appendLine("• 成功: ${result.successCount}")
            if (result.failCount > 0) {
                appendLine("• 失败: ${result.failCount}")
                if (result.failedApps.isNotEmpty()) {
                    appendLine()
                    appendLine("❌ 失败的应用:")
                    result.failedApps.take(3).forEach { app ->
                        appendLine("• $app")
                    }
                    if (result.failedApps.size > 3) {
                        appendLine("• 还有 ${result.failedApps.size - 3} 个...")
                    }
                }
            }
        }

        val dialogBuilder = AlertDialog.Builder(context)
            .setTitle(if (result.success) "🎉 导出成功" else "⚠️ 导出完成(部分失败)")
            .setMessage(message)
            .setPositiveButton("确定", null)

        // 只有当成功导出了一个文件时才显示分享按钮
        if (result.successCount == 1 && result.success) {
            dialogBuilder.setNegativeButton("分享") { _, _ ->
                shareExportedFile(result.exportPath)
            }
        }

        dialogBuilder.show()
    }

    /**
     * 打开导出文件夹
     */
    private fun openExportFolder(path: String) {
        try {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.setDataAndType(Uri.parse(path), "resource/folder")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        } catch (e: Exception) {
            // 尝试使用文件管理器打开
            try {
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.setDataAndType(Uri.parse(path), "*/*")
                context.startActivity(Intent.createChooser(intent, "选择文件管理器"))
            } catch (e2: Exception) {
                Toast.makeText(context, "无法打开文件夹，路径已复制到剪贴板", Toast.LENGTH_LONG).show()
                copyToClipboard(path, "导出路径")
            }
        }
    }

    /**
     * 分享导出的文件
     */
    private fun shareExportedFile(exportPath: String) {
        try {
            val exportFile = File(exportPath)
            if (exportFile.isFile) {
                val uri = androidx.core.content.FileProvider.getUriForFile(
                    context,
                    "${context.packageName}.fileprovider",
                    exportFile
                )

                val intent = Intent(Intent.ACTION_SEND).apply {
                    type = "application/vnd.android.package-archive"
                    putExtra(Intent.EXTRA_STREAM, uri)
                    putExtra(Intent.EXTRA_SUBJECT, "分享APK文件")
                    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                }

                context.startActivity(Intent.createChooser(intent, "分享"))
            }
        } catch (e: Exception) {
            Toast.makeText(context, "分享失败: ${e.message}", Toast.LENGTH_LONG).show()
            // 如果分享文件失败，回退到分享路径
            shareExportPath(exportPath)
        }
    }

    /**
     * 分享导出路径（备用方案）
     */
    private fun shareExportPath(path: String) {
        val intent = Intent(Intent.ACTION_SEND)
        intent.type = "text/plain"
        intent.putExtra(Intent.EXTRA_TEXT, "应用导出路径：\n$path")
        intent.putExtra(Intent.EXTRA_SUBJECT, "应用导出路径")
        context.startActivity(Intent.createChooser(intent, "分享导出路径"))
    }

    /**
     * 复制文本到剪贴板
     */
    private fun copyToClipboard(text: String, label: String) {
        val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
        val clip = android.content.ClipData.newPlainText(label, text)
        clipboard.setPrimaryClip(clip)
    }
}